/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package create_view_modify;

import cse308.entities.Degreeprogram;
import cse308.entities.Users;
import cse308.GUIUtilityClass;
import cse308.helper_classes.DegreeProgramClass;
import cse308.helper_classes.GeneralTest;
import cse308.helper_classes.UserClass;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Aaron
 */
@ManagedBean(name = "userBean")
@SessionScoped
public class UserBean implements Serializable {

    @ManagedProperty(value = "#{gUIUtilityClass}")
    private GUIUtilityClass utilities;
    private List<UserClass> userClasses;
    private List<DegreeProgramClass> degreeProgramss;
    private List<String> degreeProgramsList = new ArrayList();
    private String username;
    private String password;
    private String firstName;
    private String lastName;
    private String email;
    private boolean CIC;
    private boolean evaluator;
    private final static Logger LOG = Logger.getLogger(GUIUtilityClass.class.getName());

    public UserBean() {
        LOG.info("create userbean");
    }

    public String viewUsers() {
        userClasses = (List<UserClass>) new ArrayList();
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        Query userData = em.createNamedQuery("Users.findAll");
        List<Users> results = (List<Users>) userData.getResultList();
        for (Users i : results) {
            LOG.info("Has users in db");
            UserClass currentUser = new UserClass(i);
            userClasses.add(currentUser);
        }
        return "ViewPage";
    }

    public String editUser(UserClass user) {
        user.setEditable(true);
        return null;
    }

    public List<DegreeProgramClass> getDegreeProgramss() {
        return degreeProgramss;
    }

    public void setDegreeProgram(List<DegreeProgramClass> degreeProgramss) {
        this.degreeProgramss = degreeProgramss;
    }

    public List<String> getDegreeProgramsList() {
        return degreeProgramsList;
    }

    public void setDegreeProgramsList(List<String> degreeProgramsList) {
        this.degreeProgramsList = degreeProgramsList;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isCIC() {
        return CIC;
    }

    public void setCIC(boolean CIC) {
        this.CIC = CIC;
    }

    public boolean isEvaluator() {
        return evaluator;
    }

    public void setEvaluator(boolean evaluator) {
        this.evaluator = evaluator;
    }

    public String createUser() {
        degreeProgramss = (List<DegreeProgramClass>) new ArrayList();
        //degreeProgramsList = (List<String>) new ArrayList();


        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        LOG.info("Created new Users entity");
        Users user = new Users();
        user.setUsername(this.username);
        user.setPassword(this.password);
        user.setFirstName(this.firstName);
        user.setLastName(this.lastName);
        user.setEmail(this.email);
        user.setCicMember(this.CIC);
        user.setEvaluator(this.evaluator);
        if (utilities.checkPK(user)) {
            FacesMessage message = new FacesMessage();
            message.setDetail(GUIUtilityClass.createWarning);
            FacesContext.getCurrentInstance().addMessage("form", message);
            return "";
        }
        for (String i : degreeProgramsList) {
            Degreeprogram dp = (Degreeprogram) em.createNamedQuery("Degreeprogram.findByIdentifier").
                    setParameter("identifier", i).getResultList().get(0);
            user.getDegreeprogramCollection().add(dp);
            dp.getUsersCollection().add(user);
            em.persist(dp);
        }
        em.persist(user);
        em.getTransaction().commit();
        LOG.info("Commits entities to DB");


        return "welcome";
    }

    public String enlargeList() {
        // LOG.info(String.valueOf(degreePrograms.size()));
        //degreePrograms.add(new DegreeProgramClass());
        LOG.info("Added input box for degree program");
        return "refreshTable";
    }

    public List<UserClass> getUserClasses() {
        return userClasses;
    }

    public void setUserClasses(List<UserClass> userClasses) {
        this.userClasses = userClasses;
    }

    public String createUsers() {
        degreeProgramss = (List<DegreeProgramClass>) new ArrayList();
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        Query degreePrograms = em.createNamedQuery("Degreeprogram.findAll");
        List<Degreeprogram> results = (List<Degreeprogram>) degreePrograms.getResultList();

        for (Degreeprogram i : results) {
            DegreeProgramClass currentDegreeProgram = new DegreeProgramClass(i);
            degreeProgramss.add(currentDegreeProgram);
        }
        return "CreateUsersPage";
    }

    public String modifyEntry() {
        try {
            List<String> associatedEntity = new ArrayList();
            associatedEntity.add(Degreeprogram.class.getCanonicalName());
            List<String> associatedClass = new ArrayList();
            associatedClass.add(DegreeProgramClass.class.getCanonicalName());
            List<String> ownSets = new ArrayList();
            ownSets.add("setOwnDegreePrograms");
            List<String> allSets = new ArrayList();
            allSets.add("setAllDegreePrograms");
            this.userClasses = (List) this.utilities.generalizeModify(Users.class.getCanonicalName(),
                    UserClass.class.getCanonicalName(),
                    associatedClass, associatedEntity, ownSets, allSets);
            //this.utilities.generalizeModify(Users.class.getCanonicalName(), UserClass.class.getCanonicalName());
        } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "ModifyUser";
    }

    public String saveEntry() {
        List<GeneralTest> gt = new ArrayList();
        for (int i = 0; i < this.userClasses.size(); i++) {
            gt.add(this.userClasses.get(i));
        }
        List<String> associatedEntities = new ArrayList();
        associatedEntities.add(Degreeprogram.class.getSimpleName());
        try {
            boolean success = this.utilities.generalizedSave(Users.class.getCanonicalName(), gt, associatedEntities);
            if (!success) {
                FacesMessage message = new FacesMessage();
                message.setDetail(GUIUtilityClass.duplicateWarning);
                FacesContext.getCurrentInstance().addMessage("form", message);
                return "";
            }
        } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassNotFoundException | InstantiationException ex) {
            Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "ModifyUser";
    }

    public GUIUtilityClass getUtilities() {
        return utilities;
    }

    public void setUtilities(GUIUtilityClass utilities) {
        this.utilities = utilities;
    }
}
